package com.cipe.cmrs.controllers;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cipe.cmrs.bean.PayeeBean;
import com.cipe.cmrs.model.Payee;
import com.cipe.cmrs.service.CountryService;
import com.cipe.cmrs.service.PayeeService;

@Controller
public class PayeeController extends BaseController {

	private static final long serialVersionUID = 1815579886981166259L;

	private static final String PARAM_PAYMENT_URL = "paymentUrl";
	@Autowired
	private PayeeService payeeService;
	@Autowired
	private CountryService countryService;

	@RequestMapping("/secure/showAddPayee.do")
	public String showAddPayee(Model model, HttpServletRequest request) {
		model.addAttribute("payee", new Payee());
		model.addAllAttributes(getReferenceData());
		model.addAttribute(PARAM_PAYMENT_URL, request.getParameter(PARAM_PAYMENT_URL));
		return "addPayee";
	}

	@RequestMapping("/secure/showEditPayeeBankInfo.do")
    public String showEditPayeeBankInfo(@RequestParam Integer id, Model model, HttpServletRequest request) {
		model.addAttribute("payee", payeeService.findById(id));
		model.addAllAttributes(getReferenceData());
		model.addAttribute("mode", "editMode");
		model.addAttribute(PARAM_PAYMENT_URL, request.getParameter(PARAM_PAYMENT_URL));
		return "editPayeeBankInfo";
	}
	
	@RequestMapping("/secure/showEditPayeePersonalInfo.do")
	public String showEditPayeePersonalInfo(@RequestParam Integer id, Model model, HttpServletRequest request) {
		model.addAttribute("payee", payeeService.findById(id));
		model.addAllAttributes(getReferenceData());
		model.addAttribute("mode", "editMode");
		model.addAttribute(PARAM_PAYMENT_URL, request.getParameter(PARAM_PAYMENT_URL));
		return "addPayee";
	}
	
	@RequestMapping("/secure/showPrintPayee.do")
	public String showPrintPayee(@RequestParam Integer id, Model model) {
		Payee payee = payeeService.findById(id);
		model.addAttribute("payee", payee);
		model.addAllAttributes(getReferenceData());
		if (StringUtils.isBlank(payee.getBeneficiarytName()) || StringUtils.isBlank(payee.getBankName()) || StringUtils.isBlank(payee.getAccountNumber())) {
			model.addAttribute("message", "Fill in the required fields to print");
			return "addPayee";
		} else if (StringUtils.isBlank(payee.getBankCode()) && StringUtils.isBlank(payee.getChipsCode())) {
			model.addAttribute("message", "Fill in the required fields to print");
			return "addPayee";
		}
		return "printPayee";
	}

	@RequestMapping("/secure/savePayee.do")
	public String SavePayee(@ModelAttribute("payee") Payee payee, BindingResult result, Model model, HttpServletRequest request) {
		String view = "";
		try {
			payee = payeeService.savePayee(payee, getUserId(request));
			/*
			String prevUrl = request.getParameter(PARAM_PREV_URL);
			if (payee != null && prevUrl != null && prevUrl.contains("showAddPaymentrequest.do")) {
				view = "redirect:showAddPaymentrequest.do?payeeId=" + payee.getId();
			} else if (payee != null && prevUrl != null && prevUrl.contains("showEditPaymentrequest.do")) {
				String id = prevUrl.substring(prevUrl.indexOf("id=") + "id=".length());
				if (id.indexOf("&") != -1) {
					id = id.substring(0, id.indexOf("&"));
				}
				view = "redirect:showEditPaymentrequest.do?id=" + id + "&payeeId=" + payee.getId();
			} else if (payee.getSubmitAction() != null ? payee.getSubmitAction().equalsIgnoreCase("AddBankInfo") : false) {
				view = "addPayee";
			} else {
				view = "addPayee";
			}
			*/
			String action = request.getParameter("action");
			if("Save Bank Information".equalsIgnoreCase(action)) {
			    saveMessage(request, getText("bankinfo.message.success"));
				view = "addPayee";
			} else if(getText("editPayee.button.saveAddBankInfo").equalsIgnoreCase(action)) {
			    view = "editPayeeBankInfo";
            } else {
                saveMessage(request, getText("editPayee.message.success"));
                String paymentUrl = request.getParameter(PARAM_PAYMENT_URL);
              
                if (paymentUrl.indexOf('?') != -1 ) {
                    paymentUrl += "&payeeId=" + payee.getId();
                   
                }else if (paymentUrl.equals(""))
                {
                	paymentUrl += "showAddPaymentrequest.do?payeeId=" + payee.getId();
                }else {                	
                    paymentUrl += "?payeeId=" + payee.getId();                    
                }
                return "redirect:" + paymentUrl;
            }
		} catch (Exception e) {
			logger.error(getText("error.transaction"), e);
			saveError(request, getText("error.transaction"));
		}
		model.addAttribute("mode", request.getParameter("mode"));
		model.addAttribute("payee", payee);
		model.addAllAttributes(getReferenceData());
		model.addAttribute(PARAM_PAYMENT_URL, request.getParameter(PARAM_PAYMENT_URL));
		return view;
	}

	@RequestMapping("/secure/showPayeeList.do")
	public String showPayeeList(Model model) {
		model.addAttribute("payees", payeeService.findAll());
		return "payeeList";
	}
	
    @RequestMapping(value = "/secure/getPayee.do", method = RequestMethod.GET)
    public @ResponseBody PayeeBean getPayeeBean(@RequestParam("payeeId") Integer id) {
        return payeeService.getPayee(id);
    }
	
	@RequestMapping(value = "/secure/getPayeeList.do", method = RequestMethod.GET)
	public @ResponseBody
	Map<String, String> getPayeeList(@RequestParam(value = "payeeId", required = false) Integer includePayeeId, @RequestParam(required = false) String payeetype, Model model) {
		List<Payee> payeeList;
		if (StringUtils.isNotBlank(payeetype)) { 
			payeeList = payeeService.getActivePayeesByType(includePayeeId, payeetype);
		} else {
			payeeList = payeeService.getAllActivePayees(includePayeeId);
		}
		Map<String, String> results = new LinkedHashMap<String, String>();
		if(payeeList != null) {
			for(Payee payee : payeeList) {
				results.put(com.cipe.cmrs.util.StringUtils.INSTANCE.escape(payee.getPayeeName()), payee.getId().toString());
			}
			
		}

		return results;
	}
    
    private Map<String, Object> getReferenceData() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("countryList", countryService.getAllCountries());
        return map;
    }
}
